/*
 * Copyright (C) 2009 Dimitrios C. Michalakos
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.cs.util.binary;

import java.text.DecimalFormat;

/**
 * ByteSize can be used for calculating byte sizes.
 * @author dimitris@jmike.gr
 */
public class ByteSize {

    private final long size;

    /**
     * Constructs a new ByteSize.
     * @param size the size of a file in bytes.
     */
    public ByteSize(long size) {
        this.size = size;
    }

    /**
     * Returns this bytesize as a String.
     * @return
     */
    public String getString() {
        final DecimalFormat dec = new DecimalFormat("#.##");
        if (size <= 0L) {//i.e. -1 bytes
            return null;
        } else if (size < 1024L) {//bytes
            return String.valueOf(size) + " bytes";
        } else if (size < 1048576L) {//KB
            return dec.format(getKilobytes()) + " KB";
        } else if (size < 1073741824L) {//MB
            return dec.format(getMegabytes()) + " MB";
        } else if (size < 1099511627776L) {//GB
            return dec.format(getGigabytes()) + " GB";
        } else {
            return dec.format(getTerabytes()) + " TB";
        }
    }

    /**
     * Converts this bytesize to Kilobytes.
     * One (1) KB contains 1024 bytes.
     * @return
     */
    public double getKilobytes() {
        return (double) size / 1024;
    }

    /**
     * Converts this bytesize to Megabytes.
     * One (1) MB contains 1,048,576 bytes.
     * @return
     */
    public double getMegabytes() {
        return (double) size / 1048576;
    }

    /**
     * Converts this bytesize to Gigabytes.
     * One (1) GB contains 1,073,741,824 bytes.
     * @return
     */
    public double getGigabytes() {
        return (double) size / 1073741824;
    }

    /**
     * Returns the specified bytesize in Terabytes.
     * One (1) TB contains 1,099,511,627,776 bytes.
     * @return
     */
    public double getTerabytes() {
        return (double) size / 1099511627776L;
    }

    /**
     * Main method for testing.
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new ByteSize(1232140932859345L).getString());
    }
}
